package shark.flow.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.flowable.engine.RepositoryService;
import org.flowable.engine.repository.ProcessDefinition;
import org.flowable.engine.repository.ProcessDefinitionQuery;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import shark.flow.model.Query;
import shark.flow.service.IFlowProcessDefinitionService;
import shark.flow.vo.ProcessDefinitionQueryVo;
import shark.flow.vo.ProcessDefinitionVo;

import java.util.ArrayList;
import java.util.List;

@Service
public class FlowProcessDefinitionServiceImpl implements IFlowProcessDefinitionService {

    @Autowired
    private RepositoryService repositoryService;

    @Override
    public IPage<ProcessDefinitionVo> getPagerModel(ProcessDefinitionQueryVo params) {
        Assert.notNull(params.getQuery(), "分页查询，query对象不能为空！");
        Query query = params.getQuery();

        ProcessDefinitionQuery definitionQuery = repositoryService.createProcessDefinitionQuery();
        if (params.getName() != null) {
            definitionQuery.processDefinitionName(params.getName());
        }
        if (params.getModelKey() != null) {
            definitionQuery.processDefinitionKey(params.getModelKey());
        }

        List<ProcessDefinition> definitions = definitionQuery.listPage(query.getPageNum(), query.getPageSize());
        IPage<ProcessDefinitionVo> page = new Page<>();
        page.setTotal(definitions.size());
        page.setPages(query.getPageNum());
        page.setSize(query.getPageSize());
        page.setRecords(definitionToVoList(definitions));
        return page;
    }

    @Override
    public ProcessDefinitionVo getById(String processDefinitionId) {
        ProcessDefinition definition = repositoryService.createProcessDefinitionQuery()
                .processDefinitionId(processDefinitionId)
                .singleResult();
        return new ProcessDefinitionVo(definition);
    }

    @Override
    public boolean suspendOrActivateProcessDefinitionById(String processDefinitionId, int suspensionState) {
        boolean result = false;
        if (suspensionState == 1){
            repositoryService.suspendProcessDefinitionById(processDefinitionId, true, null);
            result = true;
        }else {
            repositoryService.activateProcessDefinitionById(processDefinitionId, true, null);
            result = true;
        }
        return true;
    }

    private List<ProcessDefinitionVo> definitionToVoList(List<ProcessDefinition> definitions) {
        List<ProcessDefinitionVo> vos = new ArrayList<>(definitions.size());
        for (ProcessDefinition definition : definitions) {
            vos.add(new ProcessDefinitionVo(definition));
        }
        return vos;
    }
}
